//
//  SEGMyServiceListViewController.m
//  ExcellentHome
//
//  Created by 陈区 on 14-9-24.
//  Copyright (c) 2014年 陈区. All rights reserved.
//

#import "SEGMyServiceListViewController.h"
#import "SEGOrderInputHttpManager.h"
#import "SEGOrderDetailController.h"
#import <Foundation/Foundation.h>

#define kPageLength 10

@interface SEGMyServiceListViewController ()<UIScrollViewDelegate>
    
@property (nonatomic, assign) __block NSInteger pageNo;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *objectArray;
    
@end

@implementation SEGMyServiceListViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageNo = 1;
    self.objectArray = [[NSMutableArray alloc] init];
    [self setupUI];
    
    WeakSelf;
    [self.tableView addWindmillWithHeaderRefreshBlock:^{
        [weakSelf headerRereshing];
    } footerRefreshBlock:^{
        [weakSelf footerRereshing];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti_refreshMyServiceList:) name:NOTI_SEGORDERMYSERVICE_LIST_REFRESH object:nil];
    // 红点逻辑监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addRedDot:) name:SEGAddReddotNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView beginHeaderRefreshing];
}

- (void)setupUI {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView setSeparatorColor:kColor_L2];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, -15, 0, 0);
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)noti_refreshMyServiceList:(NSNotification *)noti {
    [self.tableView beginHeaderRefreshing];
}

#pragma mark - 红点相关
- (void)addRedDot:(NSNotification *)notification
{
    if (notification.object) {
        NSArray *ids = notification.object;
        if (ids && [ids isKindOfClass:[NSArray class]]) {
            NSLog(@"ids = %@",ids);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSArray *serviceIdArray = [[SEGUhomeMediator sharedInstance] seg_getMyServiceIdArray:nil];
                if (serviceIdArray.count > 0) {
                    [self.tableView beginHeaderRefreshing];
                }
            });
        }
    }
}

- (void)refreshViewWithFreshStatus:(BOOL)isMore {
    
    NSDictionary* params = @{ @"communityId" : kAccountCommunityID,
                              @"custId" : [SEGUtils ValueToString:[SEGProfileManager sharedManager].profile.custId],
                              @"pageLength" : @(kPageLength),
                              @"pageNo" : [NSNumber numberWithInteger:self.pageNo]
                              };
    
    
    WeakSelf;
    [[SEGOrderInputHttpManager sharedManager] getMyOrderListDataWith:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [weakSelf.tableView stopAnimatingWindmill];
        
        NSDictionary *resultDic = result;
        if (isSuccessed) {
            if (!resultDic[@"data"]) {
                return ;
            }
            NSDictionary *paginator = resultDic[@"data"][@"paginator"];
            if ([resultDic[@"data"][@"resultList"] isKindOfClass:[NSArray class]]) {
                NSArray *dataArray = result[@"data"][@"resultList"];
                if (dataArray.count > 0) {
                    weakSelf.pageNo ++;
                }
                if (isMore) {
                    if (weakSelf.objectArray.count < [paginator[@"totalCount"] integerValue]) {
                        [weakSelf.objectArray addObjectsFromArray:dataArray];
                    } else {
                        [SEGAlertView showTmepMessageWithMessage:@"没有更多数据了！"];
                    }
                } else {
                    [weakSelf.objectArray removeAllObjects];
                    [weakSelf.objectArray addObjectsFromArray:dataArray];
                }
            }
            if ([self.objectArray count] > 0) {
                [[SEGUhomeMediator sharedInstance] seg_hideCustomProgressImage:@{@"view":self.tableView}];
            } else {
                [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView}];
            }
            [weakSelf.tableView reloadData];
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            if ([self.objectArray count] <= 0) {
                [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.tableView}];
            }
        }
    }];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing {
    self.pageNo = 1;
    [self refreshViewWithFreshStatus:NO];
}

- (void)footerRereshing {
    [self refreshViewWithFreshStatus:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.objectArray count];
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    return 71;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    NSString* cellIdentifier = @"cell";

    SEGBaseTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[SEGBaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.backgroundColor = kColor_W;

        UILabel* lbName = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 200, 16)];
        lbName.textColor = kColor_1;
        lbName.backgroundColor = [UIColor clearColor];
        lbName.textAlignment = NSTextAlignmentLeft;
        lbName.font = kFont_16;
        lbName.tag = 1001;
        [cell.contentView addSubview:lbName];

        UILabel* status = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 115, 15, 100, 16)];
        status.textColor = kColor_T;
        status.backgroundColor = [UIColor clearColor];
        status.textAlignment = NSTextAlignmentRight;
        status.font = kFont_16;
        status.tag = 1002;
        [cell.contentView addSubview:status];

        UILabel* description = [[UILabel alloc] initWithFrame:CGRectMake(15, 35, 200, FONT_DESCRIPTION_SIZE + 2)];
        description.textColor = kColor_2;
        description.backgroundColor = [UIColor clearColor];
        description.textAlignment = NSTextAlignmentLeft;
        description.font = [UIFont systemFontOfSize:FONT_DESCRIPTION_SIZE];
        description.tag = 1003;
        [cell.contentView addSubview:description];

        UILabel* lbDate = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 165, 41, 150, 15)];
        lbDate.textColor = kColor_3;
        lbDate.backgroundColor = [UIColor clearColor];
        lbDate.font = kFont_15;
        lbDate.textAlignment = NSTextAlignmentRight;
        lbDate.tag = 1004;
        [cell.contentView addSubview:lbDate];

        UIImageView* preferrdRod = [[UIImageView alloc] initWithFrame:CGRectMake(lbName.frame.size.width, lbName.frame.origin.y, 8, 8)];
        preferrdRod.tag = 1005;
        [cell.contentView addSubview:preferrdRod];
    }

    NSDictionary *orderDic = [self.objectArray objectAtIndex:indexPath.row];
    NSString *resultCode = orderDic[@"resultCode"];
    UILabel* lbName = (UILabel*)[cell.contentView viewWithTag:1001];
    UILabel* status = (UILabel*)[cell.contentView viewWithTag:1002];
    UILabel* lbDate = (UILabel*)[cell.contentView viewWithTag:1004];

    if ([resultCode isEqualToString:@"NODE_DS_OVER"] || [resultCode isEqualToString:@"NODE_DS_CANCEL"] || [resultCode isEqualToString:@"NODE_DS_CLOSE"])  {
        status.textColor = kColor_3;
    } else {
        status.textColor = kColor_T;
    }
    NSString *createTime = orderDic[@"createTime"];
    lbName.text = orderDic[@"templateInstName"];
    status.text =  orderDic[@"resultName"];
    lbDate.text =  [[NSDate dateWithTimeIntervalSince1970:[createTime doubleValue]/1000] stringWithFormat:kTimeFormatStringMin];

    UIImageView* preferrdRod = (UIImageView*)[cell.contentView viewWithTag:1005];
    preferrdRod.image = nil;
    
    NSArray *serviceIdArray = [[SEGUhomeMediator sharedInstance] seg_getMyServiceIdArray:nil];
    NSString *serviceOrderId = ValueToString([orderDic objectForKey:@"serviceOrderId"]);
    if ([serviceIdArray containsObject:serviceOrderId]) {
        [lbName sizeToFit];
        CGRect frame = preferrdRod.frame;
        frame.origin.x = lbName.frame.origin.x + lbName.frame.size.width + 8;
        preferrdRod.frame = frame;
        preferrdRod.image = [UIImage imageWithContentsOfFile:SEGPicName(@"tab_red_round")];
        preferrdRod.contentMode = UIViewContentModeScaleAspectFit;
    }
    return cell;
}
#pragma mark - Table view delegate

- (void)deselectRowDelay {
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *orderDic = [self.objectArray objectAtIndex:indexPath.row];
    
    SEGOrderDetailController *orderDetailVC = [[SEGOrderDetailController alloc] init];
    orderDetailVC.orderDict = orderDic;
    [self.navigationController pushViewController:orderDetailVC animated:YES];
    
    //删除红点
    NSString *serviceOrderId = ValueToString([orderDic objectForKey:@"serviceOrderId"]);
    [[SEGUhomeMediator sharedInstance] seg_deleteMyServiceId:@{@"serviceId":serviceOrderId ?: @""}];
    [tableView reloadData];
    //删除物业服务红点
    [[SEGUhomeMediator sharedInstance] seg_deleteRedDotWithType:@{@"type" : kMessageTypeService}];
}

@end
